<?php
/**
 * <b>RUBIK IT Solution & Development ltd.</b>
 *
 * PROJECT		: Rubik Ultimate Framework
 * @version 	: 1.1
 * COPYRIGHT    : 2008
 * ------------------------------------------------------
 * 
 * Created on	:  Jul 9, 2008
 * 
 */

// no direct access
defined ( '_FW_EXEC' ) or die ( 'Restricted access' );

RCoreImporter::cls( "html.BasePagination" );
RCoreImporter::cls( "html.HtmlControl" );

class EditableTableControl extends HtmlControl {
	
	var $_arrayViewField;
	var $_arrayRequest;
	var $_dtoName;
	
	/**
	 * dto
	 *
	 * @var AbstratctDTO
	 */
	var $_dto;
	var $_where;
	
	/**
	 * Key field
	 *
	 * @var RubikDBField
	 */
	var $_keyField;
	
	var $_orderby;
	var $_defaultOrderBy;
	var $_sort;
	var $_page;
	
	/**
	 * Database
	 *
	 * @var Database
	 */
	var $_db;
	
	// $arrayViewField = array("fieldname"=>"rule_link", "field_name"=>""); 
	function __construct($dtoName, $arrayViewField, &$arrayRequest, $name = '', $where = '', $orderBy = '', $db = null, $name = "tblAdminControl") {
		parent::__construct ( $name );
		if (empty ( $db )) {
			$this->_db = &SysDatabase::getInstance ();
		} else {
			$this->_db = &$db;
		}
		
		$this->_arrayViewField = $arrayViewField;
		$this->_dtoName = $dtoName;
		$this->_where = $where;
		$this->_arrayRequest = &$arrayRequest;
		$this->_defaultOrderBy = $orderBy;
		$this->_orderby = "x_{$name}_orderby";
		$this->_sort = "x_{$name}_sort";
		$this->_page = "x_{$name}_page";
	}
	
	/**
	 * Get data result
	 *
	 * @param sql string $orderBy
	 * @param number $recordPerPage
	 * @param number $indexPage
	 * @param string $prefix
	 * @return SelectResult
	 */
	function _getDataResult($orderBy = '', $recordPerPage = null, $indexPage = 1, $prefix = "#__") {
		$whereDto = new $this->_dtoName ( $this->_where );
		$whereDto->resetToNull ();
		$ctrlName = $this->_inputName;
		$whereDto->bind ( $this->_arrayRequest, array (), "x_{$ctrlName}_filter_" );
		$whereDto->setEmptyToNull ();
		$where = RubikDBFactory::createWhereClause ( $whereDto, "AND", true, 'LIKE', '%', '%' );
		if (! empty ( $this->_where )) {
			$where .= empty ( $where ) ? $this->_where : " AND ({$this->_where})";
		}
		
		$dto = new $this->_dtoName ( $where, $orderBy );
		$this->_dto = $dto;
		$db = $this->_db;
		$result = $db->getSelectResult ( $dto, $recordPerPage, $indexPage, $prefix );
		if ($result->isEmptyRecord ()) {
			$res = SysRequest::getResource ();
			$res->setExtend ( $this->_page, 1 );
			$result = $db->getSelectResult ( $dto, $recordPerPage, 1, $prefix );
		}
		return $result;
	}
	
	/**
	 * Create HTML table
	 *
	 * @param number $recordPerPage
	 * @param string $attributes
	 * @param string $prefix
	 */
	function createHtmlTable($recordPerPage = 10, $attributes = 'width="100%" cellspacing="1" cellpadding="0" border="0" class="tblAdminDetail"', $prefix = "#__") {
		$indexPage = $this->_arrayRequest [$this->_page];
		if (empty ( $indexPage ))
			$indexPage = 1;
		$orderBy = '';
		if (! empty ( $this->_defaultOrderBy ))
			$orderBy = 'ORDER BY ' . $this->_defaultOrderBy;
		if ($this->_arrayRequest [$this->_orderby])
			$orderBy = 'ORDER BY ' . $this->_arrayRequest [$this->_orderby] . ' ' . $this->_arrayRequest [$this->_sort];
		$res = SysRequest::getResource ();
		
		$res->removeExtendWithoutPrefix ();
		$pagerLink = $res->getLink () . "&{$this->_page}";
		
		$result = $this->_getDataResult ( $orderBy, $recordPerPage, $indexPage, $prefix );
		
		$totalItems = $result->getTotalRecords ();
		//		$recordSet = $result->recordSet;
		

		$output = '';
		$output .= "<table $attributes>";
		$output .= $this->_getFilter ( $this->_dto );
		$output .= $this->_getHeader ( $this->_dto );
		$output .= $this->getData ( $result );
		$output .= '</table>';
		$output .= $this->getPager ( $totalItems, $recordPerPage, $indexPage, $pagerLink );
		return $output;
	}
	
	/**
	 * Print the HTML table code
	 *
	 * @param number $recordPerPage
	 * @param string $attributes
	 * @param string $prefix
	 */
	function printHtmlTable($recordPerPage = 10, $attributes = 'width="100%" cellspacing="1" cellpadding="0" border="0" class="tblAdminDetail"', $prefix = "#__") {
		echo $this->createHtmlTable ( $recordPerPage, $attributes, $prefix );
	}
	
	/**
	 * Build Header Data
	 *
	 * @param DTO $dto
	 * @return 
	 */
	function _getHeader($dto) {
		$dbInfo = RubikDBFactory::getDBInfo ( $dto );
		$checkBox = $this->getCheckBoxAll ();
		
		$output = '<tr>';
		$output .= "<th width=\"20\">#</th>";
		$output .= "<th width=\"20\">$checkBox</th>";
		foreach ( $this->_arrayViewField as $key => $value ) {
			$fieldInfo = $dbInfo->getDbField ( $key );
			$fieldName = $fieldInfo->getNameWithAlias ( $dbInfo );
			
			$resource = SysRequest::cloneResource ();
			
			$resource->setExtend ( $this->_orderby, $fieldName );
			$sort = 'desc';
			if ($this->_arrayRequest [$this->_orderby] == $fieldName) {
				if (! empty ( $this->_arrayRequest [$this->_sort] ) && $this->_arrayRequest [$this->_sort] == 'desc') {
					$sort = 'asc';
				}
			}
			
			$resource->setExtend ( $this->_sort, $sort );
			
			$link = $resource->getLink ();
			$langKey = SysLanguage::_ ( $key );
			$icon = $this->getSortIcon ( $this->_arrayRequest [$this->_sort], $key );
			
			$output .= "<th><a href=\"$link\">$langKey $icon</a></th>";
		}
		$output .= '</tr>';
		return $output;
	}
	
	/**
	 * Build Filter Data
	 *
	 * @param DTO $dto
	 * @return 
	 */
	function _getFilter($dto) {
		$dbInfo = RubikDBFactory::getDBInfo ( $dto );
		
		$ctrlName = $this->_inputName;
		$output = "<tr id=\"x_{$ctrlName}_filter\">";
		$output .= "<td width=\"20\" colspan=\"2\">
						<input type=\"button\" value=\"Reset\" onclick=\"return reset_{$ctrlName}Values();\" />
						<input type=\"submit\" style=\"width: 0px; height:0px; padding:0px; margin:0px; border: 0px;\" />
						<script type=\"text/javascript\">
							function reset_{$ctrlName}Values() {
								// reset all values
								\$('#x_{$ctrlName}_filter input').val('');
								systemForm.submit();
							}
						</script>
					</td>";
		foreach ( $this->_arrayViewField as $key => $value ) {
			$fieldInfo = $dbInfo->getDbField ( $key );
			$fieldName = $fieldInfo->fieldName;
			$val = $this->_arrayRequest ["x_{$ctrlName}_filter_$fieldName"];
			
			if ($fieldInfo->isBoolean ()) {
				$inputHtml = "";
			} else {
				$inputHtml = "<input name=\"x_{$ctrlName}_filter_$fieldName\" id=\"x_{$ctrlName}_filter_$fieldName\" value=\"$val\" />";
			}
			
			$output .= "<td>$inputHtml</td>";
		}
		$output .= '</tr>';
		return $output;
	}
	
	/**
	 * Build data from recordSet
	 *
	 * @param recordSet $recordSet
	 * @return 
	 */
	function getData($result) {
		$recordSet = $result->recordSet;
		$number = 1;
		$number = $result->getIndexPage () == 1 ? $result->getIndexPage () * 1 : $result->getIndexPage () * 10 + 1;
		
		$this->_keyField = $this->getKeyFieldName ( $this->_dto );
		$keyField = $this->_keyField;
		
		$output = '';
		
		foreach ( $recordSet as $recordValue ) {
			$output .= "<tr>";
			$keyValue = $recordValue->$keyField;
			$checkBox = $this->getCheckBox ( "cid[]", $keyValue );
			$output .= "<td>$number</td>";
			$output .= "<td>$checkBox</td>";
			foreach ( $this->_arrayViewField as $key => $fieldValue ) {
				$fieldData = $recordValue->$key;
				
				if ($this->typeOfFieldNameisBoolean ( $this->_dto, $key ))
					$fieldData = $this->getBooleanData ( $recordValue->$key );
				$data = $this->createItemsLink ( $fieldData, $keyValue, $fieldValue );
				
				$output .= "<td>$data</td>";
			}
			$output .= "</tr>";
			$number ++;
		}
		return $output;
	}
	
	/**
	 * Build Pagination for table
	 *
	 * @param Number $totalItems
	 * @param Number $itemsPerPage
	 * @param Number $index
	 * @param String $link
	 * @return show pagination
	 */
	function getPager($totalItems, $itemsPerPage, $index, $link) {
		$pager = SysTemplate::getPaginationInstance ( $totalItems, $itemsPerPage, $link );
		return $pager->renderPager ( $index );
	}
	
	/**
	 * Get Sort Icon
	 *
	 * @param String $sortType
	 * @param String $key
	 * @return HTML Image Tag
	 */
	function getSortIcon($sortType = '', $key = '') {
		$currentKey = $this->_arrayRequest [$this->_orderby];
		if (! empty ( $sortType ) && $key == $currentKey) {
			$imagePath = SYS_CUR_TMPL_URL;
			if ($sortType == 'asc') {
				$image = '<img src="' . $imagePath . 'images/arrow-asc.png' . '" />';
			} else if ($sortType == 'desc') {
				$image = '<img src="' . $imagePath . 'images/arrow-desc.png' . '" />';
			}
			return $image;
		}
		return '';
	}
	
	/**
	 * Create Link for Items data
	 *
	 * @param string $data
	 * @param Number $key
	 * @param String|Object $rule
	 * @return HTML href tag
	 */
	function createItemsLink($data, $key, $rule = '') {
		$dbKeyField = $this->_keyField;
		
		if ($rule == '') {
			return $data;
		}
		if (is_array ( $rule )) {
			$link = $rule [0] . $key;
			$style = $rule [1];
		} else if (is_object ( $rule )) {
			$link = $rule->getLink () . "&$dbKeyField=" . $key;
		} else if (strpos ( $rule, '$key' ) !== false) {
			eval ( "\$link = \"{$rule}\";" );
		} else {
			$link = $rule . $key;
		}
		return "<a href=\"$link\" $style>$data</a>";
	}
	
	/**
	 * Get Field Name of PrimaryKey
	 *
	 * @param DTO $dto
	 * @return String
	 */
	function getKeyFieldName($dto) {
		$dbInfo = RubikDBFactory::getDBInfo ( $dto );
		$dbField = $dbInfo->getKeyField ();
		$dbKeyField = $dbField->fieldName;
		return $dbKeyField;
	}
	
	/**
	 * Check Field is Boolean or Not
	 *
	 * @param DTO $dto
	 * @param string $name
	 * @return true|false
	 */
	function typeOfFieldNameisBoolean($dto, $name) {
		$dbInfo = RubikDBFactory::getDBInfo ( $dto );
		$dbField = $dbInfo->getDbField ( $name );
		if ($dbField) {
			return $dbField->isBoolean ();
		}
		return false;
	}
	
	/**
	 * Build CheckBox
	 *
	 * @param String $name
	 * @param Number $value
	 * @return HTML Checkbox Tag
	 */
	function getCheckBox($name, $value) {
		return "<input type=\"checkbox\" id=\"cid\" value=\"$value\" name=\"$name\"/>";
	}
	
	/**
	 * Build Checkbox to check All
	 *
	 * @return HTML checkbox tag
	 */
	function getCheckBoxAll() {
		return "<input type=\"checkbox\" value=\"\" id=\"checkAll\" name=\"\"/>";
	}
	
	/**
	 * Get Boolean data, If true return HTML image tag
	 *
	 * @param Bool $value
	 * @return HTML image tag
	 */
	function getBooleanData($value) {
		if ($value == true) {
			$image = SYS_CUR_TMPL_URL . 'images/ico_check.gif';
			return '<img src="' . $image . '" />';
		} else {
			$image = SYS_CUR_TMPL_URL . 'images/ico_nocheck.gif';
			return '<img src="' . $image . '" />';
		}
	}
}

?>